package com.qiniu.hotkey;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.JIntellitype;
import com.qiniu.util.ImageCheck;
import com.qiniu.util.QUploadUtil;
import com.qiniu.util.ToolTip;

/**
 * 七牛文件热键上传
 * 
 * @ClassName QHotkey
 * @date 2017年11月14日 上午11:48:07
 */
public class QHotkey {

    private static final int KEY_1 = 1; //上传
    private static final int KEY_2 = 2; //插入 以md文件格式
    private static final int KEY_3 = 3; //粘贴
    
    //上传文件
    private static Map<String, File> upfiles = new HashMap<String, File>();

    public static void main(String[] args) {
	init();
    }

    private static void init() {
	// 热键组合的标识; 组合键,如果没有则为0; 该热键对应 Ctrl + Shift + U
	JIntellitype.getInstance().registerHotKey(KEY_1, JIntellitype.MOD_CONTROL + JIntellitype.MOD_SHIFT, (int) 'U');
	JIntellitype.getInstance().registerHotKey(KEY_2, JIntellitype.MOD_CONTROL + JIntellitype.MOD_SHIFT, (int) 'I');
	JIntellitype.getInstance().registerHotKey(KEY_3, JIntellitype.MOD_CONTROL + JIntellitype.MOD_SHIFT, (int) 'P');

	JIntellitype.getInstance().addHotKeyListener(new HotkeyListener() {

	    @Override
	    public void onHotKey(int flag) {
		switch (flag) {
		case KEY_1:
		    // 获取系统费剪切板
		    uploadFiles(getSysClipboardFiles());
		    break;
		case KEY_2:
		    System.out.println("insert into Markdown file");
		    setSysClipboardFiles(getText(true));
		    break;
		case KEY_3:
		    System.out.println("paste into clipboard");
		    setSysClipboardFiles(getText(false));
		    break;
		default:
		    break;
		}
	    }
	});
    }

    /**
     * 获取剪切板文件
     * 
     * @Title getSysClipboardFiles
     * @author jie_huang@woyitech.com
     * @return
     * @return List<File>
     */
    @SuppressWarnings("unchecked")
    private static List<File> getSysClipboardFiles() {
	ToolTip toolTip = ToolTip.setTipText("正在获取待处理数据...");
	System.out.println("get clipboard files");
	Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
	// 获取剪切板中的内容
	Transferable clipTf = sysClip.getContents(null);
	if (clipTf != null && clipTf.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
	    try {
		List<File> files = (List<File>) clipTf.getTransferData(DataFlavor.javaFileListFlavor);
		toolTip.clear();
		return files;
	    } catch (Exception e) {
		e.printStackTrace();
	    }
	}
	toolTip.clear();
	return Collections.emptyList();
    }
    
    /**
     * 粘贴内容
     * @Title  getText  
     * @param flag true:md格式
     * @return  String
     */
    private static String getText(boolean flag){
	StringBuilder sb = new StringBuilder();
	for(Map.Entry<String, File> f : upfiles.entrySet()){
	    if(flag){ //md
		if(ImageCheck.isImage(f.getValue())){ //图片
		    sb.append("!");
		}
		sb.append("["+f.getValue().getName()+"]");
		sb.append("(http://" + QUploadUtil.BUCKET_HOST_NAME + "/" + f.getKey()+")");
	    }else{
		sb.append("http://" + QUploadUtil.BUCKET_HOST_NAME + "/" + f.getKey());
	    }
	    sb.append("\n");
	}
	return sb.toString();
    }

    /**
     * 设置剪切板内容
     * @Title  setSysClipboardFiles 
     * @param text
     * @return  void
     */
    private static void setSysClipboardFiles(final String text) {
	Transferable trans = new Transferable() {
	    public DataFlavor[] getTransferDataFlavors() {
		return new DataFlavor[] { DataFlavor.stringFlavor };
	    }

	    public boolean isDataFlavorSupported(DataFlavor flavor) {
		return DataFlavor.stringFlavor.equals(flavor);
	    }

	    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
		if (isDataFlavorSupported(flavor))
		    return text;
		throw new UnsupportedFlavorException(flavor);
	    }

	};
	Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null);
	Robot robot = null;
	try {
	    robot = new Robot();
	} catch (AWTException e) {
	    e.printStackTrace();
	}
	// 按下crtl v键
	robot.keyPress(KeyEvent.VK_CONTROL);
	robot.keyPress(KeyEvent.VK_V);
	// 释放crtl v键
	robot.keyRelease(KeyEvent.VK_V);
	robot.keyRelease(KeyEvent.VK_CONTROL);
    }
    
    /**
     * 上传文件
     * @Title  uploadFiles 
     * @param files
     * @return  void
     */
    private static void uploadFiles(List<File> files) {
	System.out.println("upalod to qiniu");
	String name = null;
	upfiles = new HashMap<String, File>();
	for(File file:files){
	    ToolTip toolTip = ToolTip.setTipText("正在上传：\n" + file.getName());
	    name = QUploadUtil.uploadFile(file);
	    if(name != null){
		upfiles.put(name, file);
	    }
	    toolTip.clear();
	}
	System.out.println("upload completed:" + upfiles.size());
    }

    
    /**
     * 解除注册
     * @Title destroy
     * @return void
     */
    public void destroy() {
	JIntellitype.getInstance().unregisterHotKey(KEY_1);
	JIntellitype.getInstance().unregisterHotKey(KEY_2);
	System.exit(0);
    }

}
